package com.lin.web;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MessageController {

	@Autowired
	private ServletContext context;

	@RequestMapping(value = "/export", method = RequestMethod.GET)
	public String export(HttpServletRequest request,
			HttpServletResponse response) {
		try {
			// set output header
			ServletOutputStream os = response.getOutputStream();
			response.setContentType("application/vnd.ms-excel");
			response.setHeader("Content-Disposition",
					"attachment; filename=\"demo.xls\"");

			String reportLocation = context.getRealPath("WEB-INF");

			Map beans = new HashMap();
			beans.put("user", "Edwin");
			beans.put("mobile", "Jakarta, Indonesia");
			XLSTransformer transformer = new XLSTransformer();

			Workbook workbook = transformer.transformXLS(new FileInputStream(
					reportLocation + "/demo.xls"), beans);
			workbook.write(os);
			os.flush();

			return null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/index", method = RequestMethod.GET)
	public String index(HttpServletResponse response) {
		return "index";
	}
	

	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String upload(HttpServletResponse response) {
		
	Util util = new Util<Person>();
	try {
		List<Person> persons = util.parseExcelFileToBeans(new File("E:/yunsuo_resources/demo.xls"),
		                new File("E:/yunsuo_resources/person.xml"));
		 for(Person p : persons){
	            System.out.println(p.getName());
	        }
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
		return "index";
	}
	

}
